package com.huirui.server.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huirui.server.constant.LevelConstant;
import com.huirui.server.constant.StatusConstant;
import com.huirui.server.mapper.CategoryMapper;
import com.huirui.server.pojo.dto.CategoryDto;
import com.huirui.server.pojo.entity.Category;
import com.huirui.server.pojo.entity.HotSalesRanking;
import com.huirui.server.pojo.entity.ProductCategoryRelation;
import com.huirui.server.pojo.entity.Zone;
import com.huirui.server.pojo.result.PageResult;
import com.huirui.server.pojo.vo.*;
import com.huirui.server.service.CategoryService;
import com.huirui.server.service.HotSalesRankingService;
import com.huirui.server.service.ProductCategoryRelationService;
import com.huirui.server.service.ZoneService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yujun
 * @description 针对表【t_category(商品分类表)】的数据库操作Service实现
 * @createDate 2025-09-13 11:22:24
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements CategoryService {


    private final ProductCategoryRelationService productCategoryRelationService;

    @Lazy
    @Resource
    private HotSalesRankingService hotSalesRankingService;

    @Lazy
    @Resource
    private ZoneService zoneService;

    @Override
    public List<TopCategoryVo> listTopCategories() {
        List<Category> categories = lambdaQuery()
                .select(Category::getId, Category::getName)
                .eq(Category::getLevel, LevelConstant.TOP_CATEGORY)
                .eq(Category::getStatus, StatusConstant.ENABLE)
                .orderByDesc(Category::getSort)
                .orderByDesc(Category::getUpdateTime)
                .list();
        return categories
                .stream()
                .map(category -> TopCategoryVo
                        .builder()
                        .id(category.getId())
                        .name(category.getName())
                        .build())
                .toList();
    }

    @Override
    public List<SecondaryCategoryVo> listSecondaryCategories(Long id) {
        List<Category> categories = lambdaQuery()
                .select(Category::getId, Category::getName)
                .eq(Category::getLevel, LevelConstant.SECONDARY_CATEGORY)
                .eq(Category::getParentId, id)
                .eq(Category::getStatus, StatusConstant.ENABLE)
                .orderByDesc(Category::getSort)
                .orderByDesc(Category::getUpdateTime)
                .list();
        return categories
                .stream()
                .map(category -> SecondaryCategoryVo
                        .builder()
                        .id(category.getId())
                        .name(category.getName())
                        .build())
                .toList();
    }

    @Override
    public List<TertiaryCategoryVo> listTertiaryCategories(Long id) {
        List<Category> categories = lambdaQuery()
                .select(Category::getId, Category::getName, Category::getIcon)
                .eq(Category::getLevel, LevelConstant.TERTIARY_CATEGORY)
                .eq(Category::getStatus, StatusConstant.ENABLE)
                .eq(Category::getParentId, id)
                .orderByDesc(Category::getSort)
                .orderByDesc(Category::getUpdateTime)
                .list();
        return categories
                .stream()
                .map(category -> TertiaryCategoryVo
                        .builder()
                        .id(category.getId())
                        .name(category.getName())
                        .icon(category.getIcon())
                        .build()
                ).toList();
    }

    @Override
    public List<CategoryVo> getCompleteCategoryList() {
        List<Category> categories = lambdaQuery().list();
        CategoryTreeBuilder builder = new CategoryTreeBuilder();
        return builder.buildValidCategoryTree(categories);
    }

    // 核心工具类（用于构建符合条件的分类树）
    public static class CategoryTreeBuilder {

        /**
         * 构建「只包含三级分类的一级分类树」
         *
         * @param categories 数据库查询的原始分类实体列表（Category）
         * @return 符合条件的树形结构（仅一级分类，且包含二级→三级）
         */
        public List<CategoryVo> buildValidCategoryTree(List<Category> categories) {
            if (CollectionUtils.isEmpty(categories)) {
                return Collections.emptyList();
            }

            // 步骤1：将 Category 转换为 CategoryVo（字段映射：icon → imageUrl）
            List<CategoryVo> allCategoryVos = convertToCategoryVo(categories);

            // 步骤2：构建「父ID → 子分类列表」的映射，方便快速查询子分类
            Map<Long, List<CategoryVo>> parentIdToChildrenMap = buildParentChildrenMap(allCategoryVos);

            // 步骤3：从下往上过滤有效分类（先筛二级，再筛一级）
            // 3.1 筛选有效二级分类：level=2 且存在三级子分类（level=3）
            List<CategoryVo> validLevel2Vos = filterValidLevel2Vos(allCategoryVos, parentIdToChildrenMap);
            // 3.2 筛选有效一级分类：level=1 且存在有效二级子分类
            List<CategoryVo> validLevel1Vos = filterValidLevel1Vos(allCategoryVos, validLevel2Vos);

            // 步骤4：为有效分类构建树形结构（一级→二级→三级）
            return buildTree(validLevel1Vos, validLevel2Vos, allCategoryVos, parentIdToChildrenMap);
        }

        /**
         * Category 转换为 CategoryVo（处理字段映射和默认值）
         */
        private List<CategoryVo> convertToCategoryVo(List<Category> categories) {
            return categories.stream().map(category -> CategoryVo.builder()
                    .id(category.getId())
                    .name(category.getName())
                    .parentId(category.getParentId())
                    .level(category.getLevel())
                    .sort(category.getSort() != null ? category.getSort().longValue() : 0L) // smallint → Long
                    .status(category.getStatus())
                    .imageUrl(category.getIcon()) // 核心映射：icon → imageUrl
                    .createTime(category.getCreateTime())
                    .hasChildren(false) // 后续动态赋值
                    .children(new ArrayList<>()) // 初始化子列表
                    .build()).collect(Collectors.toList());
        }

        /**
         * 构建「父ID → 子分类列表」的映射
         */
        private Map<Long, List<CategoryVo>> buildParentChildrenMap(List<CategoryVo> categoryVos) {
            return categoryVos.stream()
                    .collect(Collectors.groupingBy(CategoryVo::getParentId));
        }

        /**
         * 筛选有效二级分类：level=2 且子分类中存在 level=3 的分类
         */
        private List<CategoryVo> filterValidLevel2Vos(List<CategoryVo> allVos, Map<Long, List<CategoryVo>> parentMap) {
            return allVos.stream()
                    // 只保留二级分类
                    .filter(vo -> 2 == vo.getLevel())
                    // 二级分类的子分类中必须有三级分类（level=3）
                    .filter(vo -> {
                        List<CategoryVo> children = parentMap.getOrDefault(vo.getId(), Collections.emptyList());
                        return children.stream().anyMatch(child -> 3 == child.getLevel());
                    })
                    .collect(Collectors.toList());
        }

        /**
         * 筛选有效一级分类：level=1 且子分类中存在「有效二级分类」
         */
        private List<CategoryVo> filterValidLevel1Vos(List<CategoryVo> allVos, List<CategoryVo> validLevel2Vos) {
            // 先获取有效二级分类的父ID集合（即有效一级分类的ID）
            Set<Long> validLevel1Ids = validLevel2Vos.stream()
                    .map(CategoryVo::getParentId)
                    .collect(Collectors.toSet());

            return allVos.stream()
                    // 只保留一级分类
                    .filter(vo -> 1 == vo.getLevel())
                    // 一级分类的ID必须在有效二级分类的父ID集合中（即有有效二级子分类）
                    .filter(vo -> validLevel1Ids.contains(vo.getId()))
                    .collect(Collectors.toList());
        }

        /**
         * 构建最终树形结构（一级→有效二级→三级）
         */
        private List<CategoryVo> buildTree(List<CategoryVo> validLevel1Vos,
                                           List<CategoryVo> validLevel2Vos,
                                           List<CategoryVo> allVos,
                                           Map<Long, List<CategoryVo>> parentMap) {
            // 步骤1：为有效二级分类添加三级子分类
            Map<Long, CategoryVo> level2VoMap = validLevel2Vos.stream()
                    .collect(Collectors.toMap(CategoryVo::getId, vo -> vo));

            // 遍历所有三级分类，添加到对应有效二级分类的 children 中
            allVos.stream()
                    .filter(vo -> 3 == vo.getLevel()) // 只处理三级分类
                    .forEach(level3Vo -> {
                        CategoryVo parentLevel2Vo = level2VoMap.get(level3Vo.getParentId());
                        if (parentLevel2Vo != null) {
                            parentLevel2Vo.getChildren().add(level3Vo);
                            parentLevel2Vo.setHasChildren(true); // 标记有子分类
                        }
                    });

            // 步骤2：为有效一级分类添加有效二级子分类
            Map<Long, CategoryVo> level1VoMap = validLevel1Vos.stream()
                    .collect(Collectors.toMap(CategoryVo::getId, vo -> vo));

            validLevel2Vos.forEach(level2Vo -> {
                CategoryVo parentLevel1Vo = level1VoMap.get(level2Vo.getParentId());
                if (parentLevel1Vo != null) {
                    parentLevel1Vo.getChildren().add(level2Vo);
                    parentLevel1Vo.setHasChildren(true); // 标记有子分类
                }
            });

            // 步骤3：子分类按 sort 字段排序（可选，根据需求调整）
            sortChildren(validLevel1Vos);

            return validLevel1Vos;
        }

        /**
         * 子分类按 sort 升序排序（sort 越小越靠前）
         */
        private void sortChildren(List<CategoryVo> categoryVos) {
            if (CollectionUtils.isEmpty(categoryVos)) {
                return;
            }
            // 自身子分类排序
            categoryVos.forEach(vo -> {
                if (!CollectionUtils.isEmpty(vo.getChildren())) {
                    vo.getChildren().sort(Comparator.comparingLong(CategoryVo::getSort));
                    // 递归排序子分类的子分类
                    sortChildren(vo.getChildren());
                }
            });
        }
    }


    @Override
    public List<CategoryVo> getCategoryList() {
        List<Category> categories = lambdaQuery().list();

        // 2. 转换为CategoryVo（字段映射）
        List<CategoryVo> allVos = categories.stream().map(this::convertToVo).toList();

        // 3. 按parent_id分组，便于快速查找子分类
        Map<Long, List<CategoryVo>> parentIdMap = allVos.stream()
                .collect(Collectors.groupingBy(CategoryVo::getParentId));

        // 4. 构建树形结构（一级分类 -> 二级分类 -> 三级分类）
        // 一级分类：parent_id = -1
        List<CategoryVo> level1Vos = parentIdMap.getOrDefault(-1L, new ArrayList<>());
        // 按sort排序一级分类
        level1Vos.sort(Comparator.comparing(CategoryVo::getSort).reversed());

        // 为一级分类设置二级子分类
        for (CategoryVo level1 : level1Vos) {
            List<CategoryVo> level2Vos = parentIdMap.getOrDefault(level1.getId(), new ArrayList<>());
            level2Vos.sort(Comparator.comparing(CategoryVo::getSort).reversed()); // 排序二级分类
            level1.setChildren(level2Vos);
            level1.setHasChildren(!level2Vos.isEmpty());

            // 为二级分类设置三级子分类
            for (CategoryVo level2 : level2Vos) {
                List<CategoryVo> level3Vos = parentIdMap.getOrDefault(level2.getId(), new ArrayList<>());
                level3Vos.sort(Comparator.comparing(CategoryVo::getSort).reversed()); // 排序三级分类
                level2.setChildren(level3Vos);
                level2.setHasChildren(!level3Vos.isEmpty());

                // 三级分类无下级（level=3）
                level3Vos.forEach(level3 -> {
                    level3.setChildren(new ArrayList<>());
                    level3.setHasChildren(false);
                });
            }
        }

        return level1Vos;
    }

    /**
     * 实体类转VO（字段映射）
     */
    private CategoryVo convertToVo(Category category) {
        return CategoryVo.builder()
                .id(category.getId())
                .name(category.getName())
                .createTime(category.getCreateTime())
                .status(category.getStatus())
                .sort(category.getSort() != null ? category.getSort().longValue() : 0L) // smallint转Long
                .parentId(category.getParentId())
                .imageUrl(category.getIcon()) // icon字段对应VO的imageUrl
                .level(category.getLevel())
                .build();
    }


    @Override
    @Transactional
    public void deleteCategoryById(Long id) {
        // 这个id可能是一级分类也可能是二级分类也可能是三级分类
        Integer level = lambdaQuery()
                .select(Category::getLevel)
                .eq(Category::getId, id)
                .one()
                .getLevel();
        // 三级分类直接删除
        if (level == LevelConstant.TERTIARY_CATEGORY) {
            productCategoryRelationService
                    .lambdaUpdate()
                    .eq(ProductCategoryRelation::getCategoryId, id)
                    .remove();
            removeById(id);
        }
        // 二级分类首先删除子分类，接着删除自身
        if (level == LevelConstant.SECONDARY_CATEGORY) {
            // 三级分类列表
            List<Long> list = lambdaQuery()
                    .select(Category::getId)
                    .eq(Category::getParentId, id)
                    .list().stream().map(Category::getId).toList();
            // 删除关联关系
            productCategoryRelationService
                    .lambdaUpdate()
                    .in(ProductCategoryRelation::getCategoryId, list)
                    .remove();
            lambdaUpdate()
                    .eq(Category::getParentId, id)
                    .remove();
            lambdaUpdate()
                    .eq(Category::getId, id)
                    .remove();
        }
        // 一级分类
        if (level == LevelConstant.TOP_CATEGORY) {
            List<Long> ids = new ArrayList<>();
            // 删除专区列表与热销列表
            hotSalesRankingService
                    .lambdaUpdate()
                    .eq(HotSalesRanking::getCategoryId, id)
                    .remove();
            zoneService
                    .lambdaUpdate()
                    .eq(Zone::getCategoryId, id)
                    .remove();

            // 首先查询二级分类
            lambdaQuery()
                    .select(Category::getId)
                    .eq(Category::getParentId, id)
                    .list()
                    .forEach(category -> ids.add(category.getId()));
            if (!ids.isEmpty()) {
                lambdaQuery()
                        .select(Category::getId)
                        .in(Category::getParentId, ids)
                        .list()
                        .forEach(category -> ids.add(category.getId()));
            }
            ids.add(id);
            // 删除关联关系
            productCategoryRelationService
                    .lambdaUpdate()
                    .in(ProductCategoryRelation::getCategoryId, ids)
                    .remove();
            removeByIds(ids);
        }
    }

    @Override
    public List<CategoryVo> getFirstTwoLevelsOfCategories() {
        List<CategoryVo> list = baseMapper.getCategoryList();
        list.forEach(category -> {
            if (!category.getHasChildren()) return;
            category.getChildren().forEach(categoryChild -> {
                if (!categoryChild.getHasChildren()) return;
                categoryChild.setChildren(null);
            });
        });
        return list;
    }

    @Override
    public void addCategory(CategoryDto categoryDto) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDto, category);
        if (categoryDto.getParentId() == -1) {
            category.setLevel(LevelConstant.TOP_CATEGORY);
        }
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        this.save(category);
    }

    @Override
    public void modifyCategory(CategoryDto categoryDto) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDto, category);
        category.setUpdateTime(LocalDateTime.now());
        lambdaUpdate()
                .eq(Category::getId, category.getId())
                .update(category);
    }

    @Override
    public void changeCategoryStatus(Long id, Long status) {
        lambdaUpdate()
                .eq(Category::getId, id)
                .set(Category::getStatus, status)
                .set(Category::getUpdateTime, LocalDateTime.now())
                .update();

//        if (status == StatusConstant.ENABLE) {
//            lambdaUpdate()
//                    .eq(Category::getId, id)
//                    .set(Category::getStatus, StatusConstant.ENABLE)
//                    .set(Category::getUpdateTime, LocalDateTime.now())
//                    .update();
//            return;
//        }
//
//        // 这个id可能是一级分类也可能是二级分类也可能是三级分类
//        Integer level = lambdaQuery()
//                .select(Category::getLevel)
//                .eq(Category::getId, id)
//                .one()
//                .getLevel();
//        if (level == LevelConstant.TERTIARY_CATEGORY) {
//            lambdaUpdate()
//                    .eq(Category::getId, id)
//                    .set(Category::getStatus, status)
//                    .update();
//        }
//        // 二级分类首先删除子分类，接着删除自身
//        if (level == LevelConstant.SECONDARY_CATEGORY) {
//            lambdaUpdate()
//                    .eq(Category::getParentId, id)
//                    .set(Category::getStatus, status)
//                    .update();
//            lambdaUpdate()
//                    .eq(Category::getId, id)
//                    .set(Category::getStatus, status)
//                    .update();
//        }
//        // 一级分类
//        if (level == LevelConstant.TOP_CATEGORY) {
//            List<Long> ids = new ArrayList<>();
//            // 首先查询二级分类
//            lambdaQuery()
//                    .select(Category::getId)
//                    .eq(Category::getParentId, id)
//                    .list()
//                    .forEach(category -> ids.add(category.getId()));
//            if (!ids.isEmpty()) {
//                lambdaQuery()
//                        .select(Category::getId)
//                        .in(Category::getParentId, ids)
//                        .list()
//                        .forEach(category -> ids.add(category.getId()));
//            }
//            ids.add(id);
//            lambdaUpdate()
//                    .in(Category::getId, ids)
//                    .set(Category::getStatus, status)
//                    .update();
//        }
    }


    @Override
    public List<CategoryCascaderVo> queryCategoryCascader() {
        return null;
    }

    @Override
    public List<TopCategoryVo> listTopWithoutRankingCategories() {
        return baseMapper.listTopWithoutRankingCategories();
    }

    @Override
    public void addNewCategory(CategoryDto categoryDto) {
        Category category = new Category();
        category.setLevel(categoryDto.getLevel());
        category.setParentId(categoryDto.getParentId());
        category.setName(categoryDto.getName());
        category.setSort(categoryDto.getSort());
        category.setIcon(categoryDto.getIcon());
        category.setStatus(categoryDto.getStatus());
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        save(category);
    }

    @Override
    public void updateCategory(CategoryDto categoryDto) {
        lambdaUpdate()
                .eq(Category::getId, categoryDto.getId())
                .set(Category::getName, categoryDto.getName())
                .set(Category::getSort, categoryDto.getSort())
                .set(Category::getIcon, categoryDto.getIcon())
                .set(Category::getStatus, categoryDto.getStatus())
                .update();
    }

    @Override
    public List<CategoryAnotherVo> getPopupCategoryData(Long id) {
        // 查询一级分类下的所有二级分类
        List<Category> level_2_list = lambdaQuery()
                .eq(Category::getParentId, id)
                .eq(Category::getStatus, StatusConstant.ENABLE)
                .orderByDesc(Category::getSort)
                .orderByDesc(Category::getCreateTime)
                .list();
        // 收集所有的二级分类ID查询所有的三级分类
        List<Long> level_2_ids = level_2_list
                .stream()
                .map(Category::getId)
                .toList();
        List<Category> level_3_list = lambdaQuery()
                .in(Category::getParentId, level_2_ids)
                .eq(Category::getStatus, StatusConstant.ENABLE)
                .list();
        // 将三级分类按照父ID进行分组
        Map<Long, List<Category>> level3GroupByParentId = level_3_list
                .stream()
                .collect(Collectors.groupingBy(Category::getParentId));
        return level_2_list
                .stream()
                .map(level2Category -> {
                    CategoryAnotherVo categoryAnotherVo = new CategoryAnotherVo();
                    categoryAnotherVo.setId(level2Category.getId());
                    categoryAnotherVo.setName(level2Category.getName());
                    List<CategoryAnotherVo> list = level3GroupByParentId
                            .getOrDefault(level2Category.getId(), new ArrayList<>())
                            .stream()
                            .map(level3Category -> {
                                CategoryAnotherVo level3categoryAnotherVo = new CategoryAnotherVo();
                                level3categoryAnotherVo.setId(level3Category.getId());
                                level3categoryAnotherVo.setName(level3Category.getName());
                                level3categoryAnotherVo.setImage(level3Category.getIcon());
                                return level3categoryAnotherVo;
                            })
                            .toList();
                    categoryAnotherVo.setSubCategoryList(list);
                    return categoryAnotherVo;
                })
                .toList();
    }

    @Override
    public PageResult<ProductBriefInfoVo>
    listProductListByCategoryId(
            Long categoryId,
            Integer orderBy,
            Integer priceOrder,
            Long page,
            Long pageSize
    ) {
        // TODO 只展示处于普通状态的商品
        Integer level = lambdaQuery()
                .eq(Category::getId, categoryId)
                .select(Category::getLevel)
                .one()
                .getLevel();
        // 三级分类列表
        List<Long> categoryIds = null;
        if (level == 2) {
            // 首先查询出该分类所对应的所有三级分类
            categoryIds = lambdaQuery()
                    .eq(Category::getParentId, categoryId)
                    .select(Category::getId)
                    .list()
                    .stream()
                    .map(Category::getId)
                    .toList();
        } else if (level == 3) {
            categoryIds = new ArrayList<>();
            categoryIds.add(categoryId);
        }
        IPage<ProductBriefInfoVo> iPage = new Page<>(page, pageSize);
        if (orderBy == 0) {
            // 根据销量排序
            iPage = baseMapper.listProductListByCategoryIdAndSaleCount(categoryIds, iPage);
        } else if (orderBy == 1 && priceOrder == 0) {
            // 根据价格排序升序
            iPage = baseMapper.listProductListByCategoryIdOrderByPriceAsc(categoryIds, iPage);
        } else if (orderBy == 1 && priceOrder == 1) {
            // 根据价格降序
            iPage = baseMapper.listProductListByCategoryIdOrderByPriceDesc(categoryIds, iPage);
        }
        return PageResult.from(iPage);
    }

    /**
     * 根据分类ID获取所有的子分类
     */
    @Override
    public List<Long> getCategoryIdListByCategoryId(Long categoryId) {
        Integer level = lambdaQuery()
                .eq(Category::getId, categoryId)
                .select(Category::getLevel)
                .one()
                .getLevel();
        List<Long> categoryIds = new ArrayList<>();
        categoryIds.add(categoryId);
        // 如果是二级分类如何查询出该二级分类对应的子分类
        if (level == 2) {
            List<Long> list = lambdaQuery()
                    .eq(Category::getParentId, categoryId)
                    .select(Category::getId)
                    .list()
                    .stream()
                    .map(Category::getId)
                    .toList();
            categoryIds.addAll(list);
        }
        // 如果是一级分类需要查询出二级分类以及二级分类对应的子分类
        if (level == 1) {
            List<Long> list_1 = lambdaQuery()
                    .eq(Category::getParentId, categoryId)
                    .select(Category::getId)
                    .list()
                    .stream()
                    .map(Category::getId)
                    .toList();
            if (!list_1.isEmpty()) {
                categoryIds.addAll(list_1);
                List<Long> list_2 = lambdaQuery()
                        .in(Category::getParentId, list_1)
                        .select(Category::getId)
                        .list()
                        .stream()
                        .map(Category::getId)
                        .toList();
                categoryIds.addAll(list_2);
            }
        }
        return categoryIds;
    }


    public List<CategoryVo> filterFirstLevelWithThirdLevel(List<CategoryVo> firstLevelCategories) {
        List<CategoryVo> result = new ArrayList<>();

        if (firstLevelCategories == null || firstLevelCategories.isEmpty()) {
            return result;
        }

        for (CategoryVo firstLevel : firstLevelCategories) {
            // 筛选出包含三级分类的二级分类
            List<CategoryVo> validSecondLevels = new ArrayList<>();

            if (firstLevel.getChildren() != null) {
                for (CategoryVo secondLevel : firstLevel.getChildren()) {
                    // 检查二级分类是否有三级分类
                    if (secondLevel.getChildren() != null && !secondLevel.getChildren().isEmpty()) {
                        validSecondLevels.add(secondLevel);
                    }
                }
            }

            // 如果存在包含三级分类的二级分类，则保留该一级分类
            if (!validSecondLevels.isEmpty()) {
                // 创建新的一级分类对象，避免修改原对象
                CategoryVo filteredFirstLevel = CategoryVo.builder()
                        .id(firstLevel.getId())
                        .name(firstLevel.getName())
                        .createTime(firstLevel.getCreateTime())
                        .status(firstLevel.getStatus())
                        .sort(firstLevel.getSort())
                        .parentId(firstLevel.getParentId())
                        .imageUrl(firstLevel.getImageUrl())
                        .hasChildren(true) // 因为有有效的二级分类，所以肯定有子分类
                        .children(validSecondLevels) // 只保留包含三级分类的二级分类
                        .level(firstLevel.getLevel())
                        .build();

                result.add(filteredFirstLevel);
            }
        }

        return result;
    }
}




